<template>
  <ul>
    <li v-for="tag in dataMap.tags">
        <span @click="switchTab(tag.id)" :class="tag.active ? 'active' : ''">{{tag.name}}</span>
        <img v-if="tag.canClose" class="closeImage" :src="close" @click="handleClose(tag.id)" />
        <img :src="tabsVerticalLine" />
    </li>
  </ul>
</template>

<script setup>
import { reactive,defineEmits } from 'vue';
import {useStore} from 'vuex'
import { useRouter } from 'vue-router'
const router = useRouter()
const store = useStore()

const tabsVerticalLine = '../../../public/images/tabs-vertical-line.png';
const close = '../../../public/images/close.png';

let dataMap = reactive({
    tags:store.state.tags
});

//显示哪个tab
(()=>{
    let tags = store.state.tags;
    tags.forEach((v,k)=>{
        if(v.id == store.state.activeMenuId){
            v.active = true;
        }else{
            v.active = false;
        }
    })
})()


const handleClose = (id)=>{
    let tags = store.state.tags;
    tags.forEach((v,k)=>{
        if(v.id == id){
            //如果关闭的是当前活动的tab，那么需要做一个路由跳转，切换到上一个tab
            if(v.active == true){
                let prev = tags[k - 1];
                prev.active = true;
                router.push(prev.route);
            }
            tags.splice(k,1);
        }
    })
    store.commit('updateState',['tags',tags]);
}
let switchTab = (id)=>{
    let tags = store.state.tags;
    tags.forEach((v,k)=>{
        if(v.id == id){
            v.active = true;
            router.push(v.route);
        }else{
            v.active = false;
        }
    })
    store.commit('updateState',['tags',tags]);
}
</script>

<style lang="scss" scoped>
ul{
    display:flex;
    flex-direction: row;
    li{
        .active{
            color:red;
        }
        height: 30px;
        display: flex;
        align-items: center;
        justify-content:center;
        margin-left:5px;
        span:hover{
            cursor:pointer;
            color:rgb(65, 1, 255);
        }
        .closeImage{
            width:12px;
            height:12px;
            margin-left:5px;
        }
        .closeImage:hover{
            cursor:pointer;
        }
    }
}
</style>